package main

import (
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"yunAIYI_nginxUpdate/app/service"
	"yunAIYI_nginxUpdate/app/util"
	_ "yunAIYI_nginxUpdate/boot"
	_ "yunAIYI_nginxUpdate/router"
)

var ctx = gctx.New()

// 云服务器端 用tcp client
func main() {
	//判断文件是否存在
	confs := util.Get_nginx_confgs()
	for _, v := range confs {
		v = gstr.Trim(v)

		if !gfile.Exists(v) {
			panic("nginx配置文件不存在,路径:" + v)
		}
	}

	s := g.Server()
	s.SetPort(gconv.Int(util.GetPort_server()))

	s.BindHandler("/", func(r *ghttp.Request) {
		r.Response.Write("nginx自动刷新公网ip服务正常！ 固定ip云服务器端")
	})
	s.BindHandler("/UpdateIP", func(r *ghttp.Request) {
		ip := r.Get("nowip")
		timestamp := r.Get("timestamp")
		sign := r.Get("sign")
		g.Log().Line(true).Debug(ctx, "主动推送来 ip:", ip.String())

		// 验证签名 	sign, _ := gmd5.EncryptString(ip + timestamp + sign_key)

		mysigntemp, _ := gmd5.EncryptString(ip.String() + timestamp.String() + service.Sign_key)
		state := ""

		if mysigntemp == sign.String() {
			state = "success"
			// 1.更新tcp ip  2.更新nginx
			service.UpdateIp(ip.String())
		} else {
			state = "fail"
		}

		r.Response.WriteJson(g.Map{
			"state": state,
		})
	})
	s.Run()
}
